<?php

namespace App\Providers;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot(){
        DB::listen(function($sql){
            foreach($sql->bindings as $i=>$binding){
                if($binding instanceof \DateTime){
                    $sql->bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
                }else{
                    if (is_string($binding)) {
                        $sql->bindings[$i] = "'$binding'";
                    }
                }
            }
            $query = str_replace(array('%', '?'), array('%%', '%s'), $sql->sql);
            $query = vsprintf($query, $sql->bindings);
//            echo $query;
            if(env('APP_ENV') == 'local'){
                file_put_contents(storage_path('logs').DIRECTORY_SEPARATOR.'sql.log',
                    PHP_EOL.$query.PHP_EOL,FILE_APPEND);
            }
        });

    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {

        if ($this->app->environment() !== 'production') {
            $this->app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);
        }
    }
}
